//
//  Regex.swift
//  shop
//
//  Created by 刘伟 on 2017/3/21.
//
//

import Foundation

struct MyRegex {
    let regex: NSRegularExpression?
    
    init(_ pattern: String) {
        regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    }
    
    func match(input: String) -> Bool {
        if let matches = regex?.matches(in: input,
                                        options: [],
                                        range: NSMakeRange(0, (input as NSString).length)) {
            return matches.count > 0
        }
        else {
            return false
        }
    }
}

fileprivate func checkRegex(str: String, pattern: String) -> Bool {
    let matcher = MyRegex(pattern)
    if matcher.match(input: str) {
        return true
    }
    else{
        return false
    }
}

func isPhone(_ phone: String) -> Bool {
    let pattern = "^1[0-9]{10}$"
    return checkRegex(str: phone, pattern: pattern)
}

func isUsername(_ username: String) -> Bool {
    let pattern = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}"
    return checkRegex(str: username, pattern: pattern)
}

func isPassword(_ password: String) -> Bool {
    let pattern = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$"
    return checkRegex(str: password, pattern: pattern)
}

func isEmail(_ email: String) -> Bool {
    let pattern = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"
    return checkRegex(str: email, pattern: pattern)
}

func isMoney(_ money: String) -> Bool {
//    let pattern = "^[1-9]/d*/./d*|0/./d*[1-9]/d*$"
    let pattern = "^[0-9]+\\.?[0-9]{0,2}$"
    return checkRegex(str: money, pattern: pattern)
}

// MARK: 几个常用的正则表达式
//用户名验证（允许使用小写字母、数字、下滑线、横杠，一共3~16个字符）
// ^[a-z0-9_-]{3,16}$
//Email验证
//^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$

//手机号码验证
//^1[0-9]{10}$

//URL验证
//^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$

//IP地址验证
//^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

//html标签验证
//^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$
